<?php

namespace App\Http\Controllers\Admin;

use App\Models\Classes;
use App\Models\Teacher;
use App\Models\TeacherLevel;
use App\Models\Type;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Validation\Rule;

/**
 * 班主任管理
 * Class TypeController
 * @package App\Http\Controllers\Admin
 */
class ClassTeacherController extends BaseController
{
    /**
     * 分类列表
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index()
    {

        $list = Classes::where('tc_code', '<>', '')->paginate(config('site.other.paginate'));

        return backendView('classesteacher.index', compact('list'));
    }

    public function select()
    {
        $list = Classes::where('tc_code', '')->paginate(config('site.other.paginate'));
        return backendView('classesteacher.class', compact('list'));
    }

    /**
     * 新增分类
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\View\View
     */
    public function add(Request $request, $id = null)
    {
        $class = Classes::find($id);
        $data = $request->only(['teacherCode']);
        if (!empty($data['teacherCode'])) {
            $class->tc_code = $data['teacherCode'];
            if ($class->save()) {
                return redirect()->route('admin.classTeacher.index')->with('success', __('Create success'));
            }

            return back()->with('error', __('Create failed'))->withInput();
        } else {
            $list = Teacher::where('is_logistics', 0)->doesntHave('classes')->paginate(config('site.other.paginate'));
            return backendView('classesteacher.add', compact('list', 'class'));
        }
    }

    public function delete($id = null)
    {
        /**
         * @var $type Type
         */
        $type = Type::find($id);
        if (empty($type)) {
            return back()->with('error', __('The page you requested was not found'));
        }

        if ($type->is_system == 1){
            return back()->with('error', '系统分类不能删除')->withInput();
        }
        try {
            $users = $type->users()->get();
            $agencies = $type->agencies()->get();

            if (count($users) > 0 || count($agencies) > 0) {
                return back()->with('error', '已使用的分类不能删除');
            }

            if ($type->delete()) {
                return back()->with('success', __('Delete success'));
            }
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }

        return back()->with('error', __('Delete failed'));
    }
}